<template>
    <el-card>
        <el-form :inline="true" :model="queryParams">
            <el-form-item label="公司名称">
                <el-input v-model="queryParams.companyName" placeholder="输入公司名称搜索" clearable
                    @keyup.enter="handleSearch" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
                <el-button type="success" :icon="Plus" @click="handleAdd">新增公司</el-button>
            </el-form-item>
        </el-form>

        <el-table :data="tableData" v-loading="loading" style="width: 100%" border>
            <el-table-column prop="id" label="ID" width="80" align="center" />
            <el-table-column prop="companyName" label="名称" min-width="180" />
            <el-table-column prop="contactPerson" label="联系人" width="120" />
            <el-table-column prop="contactPhone" label="联系电话" width="150" />
            <el-table-column prop="address" label="公司地址" min-width="250" show-overflow-tooltip />
            <el-table-column label="状态" width="100" align="center">
                <template #default="{ row }">
                    <el-switch v-model="row.status" :active-value="1" :inactive-value="0"
                        @change="handleStatusChange(row)" />
                </template>
            </el-table-column>
            <el-table-column label="操作" width="180" align="center" fixed="right">
                <template #default="{ row }">
                    <el-button size="small" type="primary" :icon="Edit" @click="handleEdit(row)">编辑</el-button>
                    <el-button size="small" type="danger" :icon="Delete" @click="handleDelete(row.id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <el-pagination v-model:current-page="pagination.pageNum" v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper" :total="pagination.total"
            @size-change="fetchData" @current-change="fetchData" style="margin-top: 20px; justify-content: flex-end;" />

        <el-dialog v-model="dialogVisible" :title="dialogTitle" width="50%" @close="resetForm">
            <el-form :model="form" ref="formRef" :rules="rules" label-width="100px">
                <el-form-item label="公司名称" prop="companyName">
                    <el-input v-model="form.companyName" placeholder="请输入公司名称" />
                </el-form-item>
                <el-form-item label="联系人" prop="contactPerson">
                    <el-input v-model="form.contactPerson" placeholder="请输入联系人姓名" />
                </el-form-item>
                <el-form-item label="联系电话" prop="contactPhone">
                    <el-input v-model="form.contactPhone" placeholder="请输入联系人电话" />
                </el-form-item>
                <el-form-item label="公司地址" prop="address">
                    <el-input v-model="form.address" type="textarea" placeholder="请输入公司地址" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitForm">确定</el-button>
            </template>
        </el-dialog>
    </el-card>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
// 引入所有需要的API函数
import { getCompanyPage, addCompany, updateCompany, deleteCompany, updateCompanyStatus } from '../../api/company'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus, Edit, Delete } from '@element-plus/icons-vue'

// --- 响应式状态定义 ---

const tableData = ref([])
const loading = ref(false)

// 查询参数
const queryParams = reactive({
    companyName: ''
})

// 分页参数
const pagination = reactive({
    pageNum: 1,
    pageSize: 10,
    total: 0
})

// 对话框状态
const dialogVisible = ref(false)
const dialogTitle = ref('')

// 表单引用
const formRef = ref(null)

// 表单数据模型
const initialFormState = {
    id: null,
    companyName: '',
    contactPerson: '',
    contactPhone: '',
    address: ''
}
const form = reactive({ ...initialFormState })

// 表单校验规则
const rules = {
    companyName: [{ required: true, message: '请输入公司名称', trigger: 'blur' }],
    contactPerson: [{ required: true, message: '请输入联系人', trigger: 'blur' }],
}

// --- 核心方法实现 ---

/**
 * 获取表格数据
 */
const fetchData = async () => {
    loading.value = true
    try {
        const params = {
            pageNum: pagination.pageNum,
            pageSize: pagination.pageSize,
            companyName: queryParams.companyName || null // 如果为空字符串则不传
        }
        const data = await getCompanyPage(params)
        tableData.value = data.records
        pagination.total = data.total
    } catch (error) {
        console.error("获取公司列表失败:", error)
    } finally {
        loading.value = false
    }
}

/**
 * 处理搜索
 */
const handleSearch = () => {
    pagination.pageNum = 1 // 搜索时重置到第一页
    fetchData()
}

/**
 * 重置表单到初始状态
 */
const resetForm = () => {
    Object.assign(form, initialFormState); // 重置表单数据
    formRef.value?.clearValidate(); // 清除表单验证信息
}

/**
 * 处理新增
 */
const handleAdd = () => {
    resetForm();
    dialogTitle.value = '新增医药公司';
    dialogVisible.value = true;
}

/**
 * 处理编辑
 * @param {object} row - 当前行的数据
 */
const handleEdit = (row) => {
    resetForm();
    Object.assign(form, row); // 将行数据复制到表单
    dialogTitle.value = '编辑医药公司';
    dialogVisible.value = true;
}

/**
 * 处理删除
 * @param {number} id - 要删除的公司ID
 */
const handleDelete = async (id) => {
    try {
        await ElMessageBox.confirm(
            '该公司的所有医药政策也将被删除，确定要删除这家公司吗？此操作不可逆。',
            '警告',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }
        )
        await deleteCompany(id);
        ElMessage.success('删除成功');
        fetchData(); // 重新加载数据
    } catch (error) {
        // 如果用户点击取消，confirm会抛出 'cancel' 字符串，这里无需处理
        if (error !== 'cancel') {
            console.error("删除公司失败:", error);
        }
    }
}

/**
 * 提交表单（新增或编辑）
 */
const submitForm = async () => {
    if (!formRef.value) return;

    try {
        // 1. 表单校验
        await formRef.value.validate();

        // 2. 根据 form.id 判断是新增还是修改
        if (form.id) {
            // 修改
            await updateCompany(form);
            ElMessage.success('修改成功');
        } else {
            // 新增
            await addCompany(form);
            ElMessage.success('新增成功');
        }

        // 3. 关闭对话框并刷新表格
        dialogVisible.value = false;
        fetchData();
    } catch (validationError) {
        // ElMessage.error('请检查表单输入');
        console.log('表单校验失败:', validationError);
    }
}

/**
 * 处理状态变更
 * @param {object} row - 当前行的数据
 */
const handleStatusChange = async (row) => {
    const newStatus = row.status;
    const text = newStatus === 1 ? '启用' : '禁用';

    try {
        await ElMessageBox.confirm(
            `确定要"${text}"这家公司吗？`,
            '状态变更确认',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }
        );

        // 调用API更新状态
        await updateCompanyStatus(row.id, newStatus);
        ElMessage.success(`${text}成功`);

        // 这里我们不需要调用 fetchData() 重新加载整个表格
        // 因为 el-switch 的 v-model 已经更新了当前行 row.status 的值,UI响应更迅速

    } catch (error) {
        // 如果用户点击取消，恢复开关原始状态
        if (error === 'cancel') {
            row.status = newStatus === 1 ? 0 : 1;
        } else {
            console.error(`更新状态失败:`, error);
            ElMessage.error(`${text}失败`);
            // 如果API调用失败，也恢复开关状态
            row.status = newStatus === 1 ? 0 : 1;
        }
    }
};

// --- 生命周期钩子 ---

// 组件挂载时自动加载第一页数据
onMounted(() => {
    fetchData()
})
</script>

<style scoped>
/* 可根据需要添加一些局部样式 */
.el-form {
    margin-bottom: 20px;
}
</style>